/*
 * Copyright (c) 2017, dhl and/or its affiliates. All rights reserved.
 * dhl PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 */
package com.xd.cloud.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xd.cloud.service.core.DataAuthorityService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xd.cloud.common.Constants;
import com.xd.cloud.common.bean.MessageBean;
import com.xd.cloud.common.util.MD5;
import com.xd.cloud.entity.core.User;
import com.xd.cloud.entity.core.UserRole;
import com.xd.cloud.service.core.UserRoleService;
import com.xd.cloud.service.core.UserService;

/**
 * 所有不需要登陆的相关action
 *
 * @author dhl
 * @since V1.0
 */
@Controller
@RequestMapping("/vehicle")
public class VehicleController extends BaseController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private DataAuthorityService dataAuthorityService;


    /**
	 * 前台_首页
	 */
	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest request,
							  @RequestParam(value = "menu",defaultValue = "index",required = false) String menu,
							  @RequestParam(value = "module",defaultValue = "monitor",required = false) String module,
							  @RequestParam(value = "subModule",defaultValue = "location",required = false) String subModule){

		String url = "vehicle/index";
		ModelAndView mv = new ModelAndView(url);
        User sessionUser = getSessionUser(request);
        List<UserRole> byuseridNoStatus = userRoleService.getByuseridNoStatus(sessionUser.getId());
        if(byuseridNoStatus.size()>0){
            UserRole userRole = byuseridNoStatus.get(0);
            String authority = userRole.getRole().getAuthority();
            mv.addObject("authority", authority);
        }
		mv.addObject("menu",menu);
		mv.addObject("module",module);
		mv.addObject("subModule",subModule);
		return mv;
	}

	/**
	 * 后台管理_首页
	 */
	@RequestMapping("/adminIndex")
	public ModelAndView adminIndex(HttpServletRequest request,
							  @RequestParam(value = "menu",defaultValue = "common",required = false) String menu,
							  @RequestParam(value = "module",defaultValue = "sys",required = false) String module,
							  @RequestParam(value = "subModule",defaultValue = "index",required = false) String subModule){
        String url = "vehicle/adminIndex";
        ModelAndView mv = new ModelAndView(url);
        User sessionUser = getSessionUser(request);
        List<UserRole> byuseridNoStatus = userRoleService.getByuseridNoStatus(sessionUser.getId());
        if(byuseridNoStatus.size()>0){
            UserRole userRole = byuseridNoStatus.get(0);
            String authority = userRole.getRole().getAuthority();
            mv.addObject("authority", authority);
        }
        mv.addObject("menu", menu);
        mv.addObject("module", module);
        mv.addObject("subModule", subModule);
        return mv;
	}
    /**
     * 跳转到错误页面
     */
    @RequestMapping("/error")
    public ModelAndView error(HttpServletRequest request,
                              HttpServletResponse response) {
        String url = "error";
        ModelAndView mv = new ModelAndView(url);
        return mv;
    }
	
    /**
     * 跳转到登陆界面
     *
     * @param request
     * @return
     */
    @RequestMapping("/tologin")
    public ModelAndView tologin(HttpServletRequest request) {

        String url = "vehicle/login";
        ModelAndView mv = new ModelAndView(url);
        return mv;
    }

    /**
     * 判断用户是否登录
     *
     * @param user:用户
     * @return
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public Object login(HttpServletRequest request,
                        HttpServletResponse response, User user) {
        Subject users = SecurityUtils.getSubject();
        MD5 md5 = new MD5();
        String password = md5.getMD5ofStr(user.getPassword());
        UsernamePasswordToken token = new UsernamePasswordToken(
                user.getAccount(), password);
        token.setRememberMe(true);
        try {
            users.login(token);
            // boolean flag = users.isAuthenticated();
            User tuser = userService.getByUserAccount(user.getAccount());
            //设置数据访问规则
            String dataAuthority = dataAuthorityService.getDataAuthorityByUserId(tuser.getId());
            tuser.setDataRule(dataAuthority);
            setSessionUser(request, tuser);

            SavedRequest savedRequest = WebUtils.getSavedRequest(request);
            String redirecturl = null;
            // 获取保存的URL
            if (savedRequest != null && savedRequest.getRequestUrl() != null) {
                redirecturl = savedRequest.getRequestUrl();
            }
            return new MessageBean(true, "", redirecturl);
        } catch (UnknownAccountException e) {
            token.clear();
            return new MessageBean(false, Constants.ERROR_7);
        } catch (IncorrectCredentialsException ee) {
            token.clear();
            return new MessageBean(false, Constants.ERROR_8);
        } catch (LockedAccountException eee)
        {
        	token.clear();
        	return new MessageBean(false, Constants.ERROR_6);
        }
        
    }

    @RequestMapping(value = "/logout")
    public ModelAndView logout(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
        }
        setSessionUser(request, null);
        String url = "redirect:/vehicle/tologin";
        ModelAndView mv = new ModelAndView(url);
        return mv;
    }

}
